package main

import (
	"bufio"
	"encoding/hex"
	"flag"
	"fmt"
	"gitee.com/yangzx6606/core/conn/client"
	log "github.com/golang/glog"
	"os"
	"time"
)

type ExampleClient struct {
	c client.Client
}

func (c *ExampleClient) OnData(packet *client.Packet, args any) {
	if packet.Type == client.PacketTypeConnected {
		log.Info("连接成功")
	} else if packet.Type == client.PacketTypeConnectLost {
		log.Info("连接断开")
	} else if packet.Type == client.PacketTypeData {
		log.Info("[RX]", hex.EncodeToString(packet.Data))
	}
}

func (c *ExampleClient) Open() error {
	c.c.AttachObserver(c, nil)
	return c.c.Open()
}

func (c *ExampleClient) Write(data []byte) error {
	log.Info("[TX]", hex.EncodeToString(data))
	return c.c.Write(&client.Packet{Type: client.PacketTypeData, Data: data})
}

func (c *ExampleClient) Close() {
	c.c.Close()
}

func main() {
	address := "127.0.0.1:8092"
	mode := "quic"
	flag.StringVar(&mode, "mode", mode, "运行模式可选：'tcp'/'quic'")
	flag.StringVar(&address, "address", address, "监听地址，如：:8092")
	flag.Parse()

	var c *ExampleClient
	if mode == "quic" {
		c = &ExampleClient{c: client.NewQuicClient(address, "media")}
	}
	if c == nil {
		log.Error("模式不支持")
	}

	err := c.Open()
	if err != nil {
		log.Error("启动客户端连接失败：", err)
		return
	}

	go func() {
		i := 0
		for i < 10000 {
			i++
			_ = c.Write([]byte(fmt.Sprintf("第%d条测试消息", i)))
			time.Sleep(time.Second * 5)
		}
	}()
	reader := bufio.NewReader(os.Stdin)
	for {
		cmd, _ := reader.ReadString('\n')
		if cmd == "quit\r\n" {
			break
		}
		err = c.Write([]byte(cmd))
		if err != nil {
			log.Error("发送数据失败：", err)
		}
	}
	c.Close()
}
